 $(function(){  
	 var queryString = decodeURI(window.location.search.substr(1));
	 var isAuth=matchQueryString(queryString,"isAuth");
	 var loadPrompt;
	 
	 var connect="1";
	 var closed=true;
	 window.addEventListener('message',function(e){
		 if(e.data==='duyixia'){
			 closed=false;
		 }	 
         window.parent.postMessage(connect,'*');
     },false);
	 
	 
	 function requestDial(caller,callerName,called,calledType,calledName,backUrl){
		 var sessionId,intervalId,
		 tip=$('#dialtip'),
		 callerConnected=false,//主叫是否接听
	     status = {
	        'NEW': '准备呼叫name(tel)<span class="dotting"></span>',
	        'INVITE': '正在呼叫name(tel)<span class="dotting"></span>',
	        'RINGING': '正在呼叫name(tel)<span class="dotting"></span>',
	        'ANSWERED': 'name(tel)已接听<span class="dotting"></span>',
	        'DISCONNECTED':'name(tel)已挂断<span class="dotting"></span>',
	        'FAILED': 'name(tel)已退出通话<span class="dotting"></span>',
	        'CANCEL': 'name(tel)取消呼叫<span class="dotting"></span>'
	     },
		 callerStatus={
			name:callerName,
			tel:caller,
			status:'NEW'
		 },
		 calleeStatus={
			name:calledName,
			tel:called,
			status:'NEW'
		 };
	     $('#lcalled').text(calledName.charAt(0));
	     $('#called').text(calledName);
	     $.ajax({
	         type : "get",
	         url : localCache.getSessionItem('dial_url'),
	         dataType : "json",
	         data : {
	        	 app_key:localCache.getSessionItem('account_identifer'),
	        	 cust_account:localCache.getSessionItem('periphery_account'),
	        	 sign:localCache.getSessionItem('sign'),
	        	 timestamp:localCache.getSessionItem('timestamp'),
	        	 caller:caller,
	        	 called:called,
	        	 ext_terminalCode:localCache.getSessionItem('userId')
	         },
	         success : function(rc) {
	           if(rc.result==='0'){
	        	    sessionId=rc.sessionId;
	        	    //本地缓存通话记录
	                meetCache.storageMeet({
	                	session_id:sessionId,
	                	status:'fail',
	                	type:'Dial',
	                	time:new Date().getDateTime(),
	                	data:[
	                	    {"name":localCache.getSessionItem("callerName"),"telephone":caller,"type":"main"},
	                	    {"name":calledName,"telephone":called,"type":calledType}
	                	]
	                });
	                tip.html(status[callerStatus.status].replace("name",callerName).replace("tel",caller));
	                //设置定时器定期获取通话状态
	        	    intervalId=window.setInterval(function(){
	                $.ajax({
	                    type: "get",
	                    dataType: "jsonp",
	                    url: localCache.getSessionItem('statusUrl'),
	                    data: {
	                        "sessionid": sessionId
	                    },
	                    success: function (json) {
	                        if (json['result'] === '0') {
	                        	var data=json['data'];
	                        	for(var i=0,l=data.length;i<l;i++){
	                        		var statusData=data[i],callee=statusData.callee;
	                                if(callee.substring(0,2)=='86'){
	                                	callee=callee.substring(2);
	                                }else if(callee.substring(0,1)=='0'){
	                                	callee=callee.substring(1);
	                                }
	                                if(!callerConnected){//主叫未接听
	                                	if(caller===callee){//为主叫的状态
	                                		if(statusData.call_state!==callerStatus.status){//状态发生了变化
	                                			tip.html(status[statusData.call_state].replace("name",callerName).replace("tel",caller));
	                                			callerStatus.status=statusData.call_state;//设置新的状态
	                                			if('ANSWERED'===callerStatus.status)//主叫接听
	                                				callerConnected=true;
	                                			else if('DISCONNECTED,FAILED,CANCEL'.indexOf(callerStatus.status)>-1){
	                                				if(intervalId){
	                                    				clearInterval(intervalId);
	                                					intervalId=null;
	                                				}
	                         	    	           connect='0';
		                            				if(closed){
			                            				setTimeout(function(){
			                              					if(backUrl){
			                                					  location.assign(backUrl);
			                                					}else
			                                    				  history.back();
			                            				},2000);	
		                            				}
	                                			}
	                                			break;
	                                		}
	                                	}else
	                                		continue;
	                                }else{//主叫已接听
	                                	var target=calleeStatus;
	                                	if(caller===callee)
	                                		target=callerStatus;
	                            		if(statusData.call_state!==target.status){//状态发生了变化
	                            			tip.html(status[statusData.call_state].replace("name",target.name).replace("tel",target.tel));
	                            			target.status=statusData.call_state;//设置新的状态
	                            			if(target===calleeStatus&&"ANSWERED"===target.status){//被叫已经接听，通话成功
												meetCache.setMeetStatus(sessionId,'success');
	                            			}else if('DISCONNECTED,FAILED,CANCEL'.indexOf(target.status)>-1){//挂断或未接通
	                            				if(intervalId){
	                                				clearInterval(intervalId);
	                            					intervalId=null;
	                            				}  
	                     	    	           connect='0';   
	                            				if(closed){
		                            				setTimeout(function(){
		                              					if(backUrl){
		                                					  location.assign(backUrl);
		                                					}else
		                                    				  history.back();
		                            				},2000);	
	                            				}
	                            			}
	                        				break;
	                            		}
	                                }
	                        	}
	                        }
	                    }
	                   });
	    	          },1000
	                );
	           }else{
	        	   new UserPrompt(rc.describe,function(){
 	    	           connect='0';
       				if(closed){
       					tip.html('拨号发起失败，即将关闭当前页面...');
        				setTimeout(function(){
          					if(backUrl){
            					  location.assign(backUrl);
            					}else
                				  history.back();
        				},2000);	
    				}
	        	   }); 
	           }
	           
	         }
	       });
	     $('#stop').on('click',function(){
	    	 if(sessionId){
	    	     $.ajax({
	    	         type : "get",
	    	         url : localCache.getSessionItem('dialStop_url'),
	    	         dataType : "json",
	    	         data : {
	    	        	 sessionid:sessionId
	    	         },
	    	         beforeSend:function(){
	    	             tip.html('通话结束中<span class="dotting"></span>');
	    	         },
	    	         success : function(rc) {
	    	           connect='0';   
	    	           if(rc.result==='0'){
	      	        	   sessionId=null;
	          			   clearInterval(intervalId);
	      	        	   if(closed){
		       				   if(backUrl){
			      					  location.assign(backUrl);
			      				   }else
			          				  history.back();
	      	        	   }
	    	           }
	    	         }
		         });
	    	 }
	     });
	 }
	 
	 if(isAuth==='1'){//需要鉴权
         function createMptyMeeting(callerObject,calleds){
             $.ajax({  
                 type: "get",
                 dataType: "jsonp",
                 url: abilityUrl + "/MPTYv4/createConference.do",
                 async: true,
                 data: {
                     'cust_account': localCache.getSessionItem("account_identify"),
                     'caller': callerObject.telephone,
                     'ext_terminalCode': localCache.getSessionItem("userId"),
                     'called': calleds.telephone,
                     'timestamp': localCache.getSessionItem("timestamp"),
                     'sign': localCache.getSessionItem("sign"),
                     'app_key':localCache.getSessionItem("account_identifer")
                 },
					beforeSend:function(){
						if(!loadPrompt)
						  loadPrompt=new LoadPrompt('发起会议中...');
					},
                 success: function (json) {
                     if (json['result'] == '0') {
                         //拼写参与人和相应信息
                         var jsonString = [];
                         var jsonData = {};
                         jsonData.data = [];
                         jsonData.data.push(callerObject);
                         jsonData.data.push(calleds);
                         jsonData.session_id = json['sessionId'];
                         jsonData.type='TalksV2';
                         jsonString.push(jsonData);
                         var json = eval(jsonString);

                         //拼写向本地存储记录信息
                         //默认通话状态为失败
                         jsonData.status='fail';
                         //写入时间
                         jsonData.time=new Date().getDateTime();
                         //写入本地存储
                         meetCache.storageMeet(jsonData);
                         location.assign("meeting.html?data=" + JSON.stringify(json));
                     } else {
                         new UserPrompt(json['describe']+"请稍后再试！");  
                     }
                 },
                 complete: function () {
						if(loadPrompt){
							loadPrompt.close();
							loadPrompt=null;
						}
                 }
             });
         }
		 $('#two_call').css('display','none');
		 var called=getJSONParsedObject(localCache.getSessionItem("contacts"),''),
         abilityUrl = localCache.getSessionItem("abilityUrl"),
         account_identify = localCache.getSessionItem("account_identify"),
         callerName=localCache.getSessionItem("callerName"),
         caller=localCache.getSessionItem("caller"),
		 len=called.length;
		 if(len>1){
			new UserPrompt('两方拨号只能添加1个被叫号码');
			return;
		 }else if(len===0){
			new UserPrompt('请添加1个被叫号码');
			return;
		 }else{
			validateResult = validateNumber(called[0].telephone);
			if (!validateResult.success) {
				new UserPrompt(validateResult.msg);
				return;
			}
            $.ajax({  
                type: "get",
                dataType: "jsonp",
                url: abilityUrl + "/v4/h5/getAccountBalancesByAbilityType.do",
                async: true,
                data: {
                    'cust_account': account_identify,
                    'ability_type':'mpty,dial'
                },
                beforeSend:function(){
					loadPrompt=new LoadPrompt('发起会议中...');
                },
                success: function (json) {
                    if (json['result'] == '0000') {
                     if(json['dial']==='0'&&json['mpty']==='1'){//两方通话没有余额，多方通话有余额
                   		 if(loadPrompt){
    							loadPrompt.close();
    							loadPrompt=null;
    						 }
                            new ConfirmPrompt('您的两方通话额度已用尽，是否使用多方通话通道发起通话？',{
                           	 save:function(prompt){
                           		prompt.close();
                                createMptyMeeting({name:callerName,telephone:caller,type:'main'},called[0]);
                           	 } 
                            }); 
                   	 }else{
                		 $('#two_call').css('display','block');    
                		 var dataObject={
                			data:[{
                				name:callerName,
                				telephone:caller,
                				type:'main'
                			},called[0]]	 
                		 };
                		 requestDial(caller,callerName,called[0].telephone,called[0].type,called[0].name,'Launch_meeting.html?data='+JSON.stringify(dataObject));
                   	 }                          		                            	 
                    }  
                },
                error:function(){
               	 if(loadPrompt){
						loadPrompt.close();
						loadPrompt=null;
					}
                },
                complete:function(){  
                  	 if(loadPrompt){
 						loadPrompt.close();
 						loadPrompt=null;
 					}
                 }
            });
		 }
	 }else{
		 var caller=matchQueryString(queryString,"caller"),
		 callerName=localCache.getSessionItem("callerName"),  
		 called=matchQueryString(queryString,"called"),
		 calledType=matchQueryString(queryString,"calledType"),
		 calledName=matchQueryString(queryString,"calledName");
		 requestDial(caller,callerName,called,calledType,calledName);
	 }

 })
	
